package com.ztorn.common.util;

import com.ztorn.common.assertion.Asserts;
import com.ztorn.common.model.SystemConfiguration;

import java.util.Map;
import java.util.regex.Pattern;

public class SqlUtil {

    private static final String SEMICOLON = ";";

    public static String[] getStatements(String sql) {
        return getStatements(sql, SystemConfiguration.getInstances().getSqlSeparator());
    }

    public static String[] getStatements(String sql, String sqlSeparator) {
        if (Asserts.isNullString(sql)) {
            return new String[0];
        }

        String[] splits = sql.replace(";\r\n", ";\n").split(sqlSeparator);
        String lastStatement = splits[splits.length - 1].trim();
        if (lastStatement.endsWith(SEMICOLON)) {
            splits[splits.length - 1] = lastStatement.substring(0, lastStatement.length() - 1);
        }

        return splits;
    }

    public static String removeNote(String sql) {

        if (Asserts.isNotNullString(sql)) {
            // Remove the special-space characters
            sql = sql.replaceAll("\u00A0", " ").replaceAll("[\r\n]+", "\n");
            // Remove annotations Support '--aa' , '/**aaa*/' , '//aa' , '#aaa'
            Pattern p = Pattern.compile("(?ms)('(?:''|[^'])*')|--.*?$|//.*?$|/\\*.*?\\*/|#.*?$|");
            String presult = p.matcher(sql).replaceAll("$1");
            return presult.trim();
        }
        return sql;
    }

    public static String replaceAllParam(String sql, String name, String value) {
        return sql.replaceAll("\\$\\{" + name + "\\}", value);
    }

    public static String replaceAllParam(String sql, Map<String, String> values) {
        for (Map.Entry<String, String> entry : values.entrySet()) {
            sql = replaceAllParam(sql, entry.getKey(), entry.getValue());
        }
        return sql;
    }

}
